﻿using OfficeOpenXml;
using OfficeOpenXml.Style;
using OfficeOpenXml.Table;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Util.Excel
{
    public class EPPlusExcel : IExcelAssistant
    {
        /// <summary>
        /// 把实体列表转抱成Excel流
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        public Stream Collection2ExcelStream<T>(List<T> source, string sheetName) where T : class, new()
        {
            byte[] bytes = Collection2ExcelBytes(source, sheetName);
            MemoryStream ms = new MemoryStream(bytes);
            return ms;
        }

        /// <summary>
        /// 把实体列表转抱成Excel流
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        public async Task<Stream> Collection2ExcelStreamAsync<T>(List<T> source, string sheetName) where T : class, new()
        {
            byte[] bytes = await Collection2ExcelBytesAsync(source, sheetName);
            MemoryStream ms = new MemoryStream(bytes);
            return ms;
        }

        /// <summary>
        /// 把实体列表转换成Excel字节
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public byte[] Collection2ExcelBytes<T>(List<T> source, string sheetName) where T : class, new()
        {
            using (var packge = new ExcelPackage())
            {
                var sheet = packge.Workbook.Worksheets.Add(sheetName);
                sheet.Cells.LoadFromCollection(source, true, TableStyles.Medium27);

                byte[] buffer = packge.GetAsByteArray();
                return buffer;
            }
        }

        /// <summary>
        /// 把实体列表转换成Excel字节
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public async Task<byte[]> Collection2ExcelBytesAsync<T>(List<T> source, string sheetName) where T : class, new()
        {
            using (var packge = new ExcelPackage())
            {
                var sheet = packge.Workbook.Worksheets.Add(sheetName);
                sheet.Cells.LoadFromCollection(source, true, TableStyles.Medium27);

                byte[] buffer = await packge.GetAsByteArrayAsync();
                return buffer;
            }
        }
    }
}
